package cn.com.bo.util.io;

public class BytesUtils
{
    private static final byte[] hex = "0123456789abcdef".getBytes();

    public static long byte2Long(final byte[] b,int len)
    {
        long res = 0;
        int tem = 0;
        for (int i = 0; i < len; i++)
        {
            res <<= 8;
            tem = b[i] & 0xff;
            res |= tem;
        }

        return res;
    }
    
    // 从字节数组到十六进制字符串转换
    public static String bytesToHexString(final byte[] b)
    {
        byte[] buff = new byte[2 * b.length];

        for (int i = 0; i < b.length; i++)
        {
            buff[2 * i] = hex[(b[i] >> 4) & 0x0f];
            buff[2 * i + 1] = hex[b[i] & 0x0f];
        }

        return new String(buff);
    }

    /**
     * 将指定字符串src，以每两个字符分割转换为16进制形式 如："2B44EFD9" --> byte[]{0x2B, 0x44, 0xEF,
     * 0xD9}
     * @param src String
     * @return byte[]
     */
    public static byte[] hexString2Bytes(final String src)
    {
        int length = src.length() / 2;
        byte[] ret = new byte[length];
        byte[] tmp = src.getBytes();

        for (int i = 0; i < length; i++)
        {
            ret[i] = uniteBytes(tmp[i * 2], tmp[i * 2 + 1]);
        }

        return ret;
    }

    /**
     * 将两个ASCII字符合成一个字节； 如："EF"--> 0xEF
     * @param src0 byte
     * @param src1 byte
     * @return byte
     */
    private static byte uniteBytes(final byte src0, final byte src1)
    {
        byte _b0 = Byte.decode("0x" + new String(new byte[]
        { src0 })).byteValue();
        _b0 = (byte) (_b0 << 4);

        byte _b1 = Byte.decode("0x" + new String(new byte[]
        { src1 })).byteValue();

        byte ret = (byte) (_b0 ^ _b1);

        return ret;
    }
    
}
